package com.xxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.config.api.AuditAware;
import com.xxx.config.exception.GenExceptCode;
import com.xxx.config.exception.ServiceException;
import com.xxx.entity.UserEntity;
import com.xxx.mapper.UserMapper;
import com.xxx.service.UserService;
import com.xxx.util.CopyUtil;
import com.xxx.util.jwt.JwtUtil;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity>
        implements UserService {

    @Override
    public void edit(UserEntity entity) {
        Integer id = AuditAware.getUserId();
        if (entity == null) {
            throw new ServiceException(GenExceptCode.Request_Param.name(), "参数错误");
        }
        UserEntity oldEntity = this.getById(id);
        if (oldEntity == null) {
            throw new ServiceException(GenExceptCode.Request_Param.name(), "用户不存在！");
        }
        entity.setId(id);
        CopyUtil.copyNotNullProperties(entity, oldEntity);
        this.updateById(oldEntity);
    }

    @Override
    public UserEntity mine() {
        Integer id = AuditAware.getUserId();
        if (id == null) {
            throw new ServiceException(GenExceptCode.Request_Param.name(), "用户id不能为空！");
        }
        return this.getById(id);
    }

    @Override
    public String login(String username, String password) {
        if (username == null || password == null) {
            throw new ServiceException(GenExceptCode.Request_Param.name(), "账户或密码不能为空！");
        }
        UserEntity userEntity = this.getOneByUsername(username, password);
        if (userEntity == null) {
            throw new ServiceException(GenExceptCode.Request_Param.name(), "账户或密码错误！");
        }
        AuditAware.setUserId(userEntity.getId());
        // -1 永不过期
        return JwtUtil.generateToken(userEntity.getId(), -1);
        // TODO 生成token后保存到redis
    }

    @Override
    public void logout() {
        // TODO 删除redis
    }

    @Override
    public void register(UserEntity entity) {
        System.out.println(entity);
    }

    private UserEntity getOneByUsername(String username, String password) {
        QueryWrapper<UserEntity> query = new QueryWrapper<>();
        query.lambda().eq(UserEntity::getName, username).eq(UserEntity::getPassword, password);
        UserEntity userEntity = this.getOne(query);
        if (userEntity == null) {
            query = new QueryWrapper<>();
            query.lambda().eq(UserEntity::getPhone, username).eq(UserEntity::getPassword, password);
            userEntity = this.getOne(query);
        }
        return userEntity;
    }
}




